package com.doform.android.xianggucheng.activity.downorder;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.activity.BaseTitleActivity;
import com.doform.android.xianggucheng.bean.OrderQueryAllBean;
import com.doform.android.xianggucheng.bean.OrderQueryBean;
import com.doform.android.xianggucheng.bean.OrderQueryBean2;
import com.doform.android.xianggucheng.bean.QueryLibraryBean;
import com.doform.android.xianggucheng.bean.WorkerBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqListLibraryBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryOrder;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryOrder2;
import com.doform.android.xianggucheng.bean.request_bean.ReqUpdateOrder;
import com.doform.android.xianggucheng.popwindow.CommonDialog;
import com.doform.android.xianggucheng.popwindow.CommonPopWindow;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.utils.RexUtils;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiFunction;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/5/17.
 */

public class OrderDetailActivity extends BaseTitleActivity {

    @BindView(R.id.tv_order_num)
    TextView tv_order_num;

    @BindView(R.id.tv_order_add_date)
    TextView tv_order_add_date;

    @BindView(R.id.tv_pay_method)
    TextView tv_pay_method;

    @BindView(R.id.tv_yingshou)
    TextView tv_yingshou;

    @BindView(R.id.et_shishou)
    EditText tv_shishou;

    @BindView(R.id.tv_name)
    TextView tv_name;

    @BindView(R.id.tv_phone)
    TextView tv_phone;

    @BindView(R.id.tv_address)
    TextView tv_address;

    @BindView(R.id.tv_library)
    TextView tv_library;

    @BindView(R.id.tv_person)
    TextView tv_person;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.btn_commit)
    Button btn_commit;

    @BindView(R.id.iv_pay_method)
    ImageView mIvPayMethod;

    @BindView(R.id.rl_pay_method)
    RelativeLayout mRlPayMethod;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    @BindView(R.id.ll)
    LinearLayout mLl;

    private List<OrderQueryBean2> datas = new ArrayList<>();
    private CommonAdapter<OrderQueryBean2> commonAdapter;
    private String mOrderId, mOrderGuid;
    private static final String RECEIVE = "receive";
    private static final String SEND = "send";
    private static final String CANCEL = "cancel";
    private DecimalFormat df = new DecimalFormat("#.00");
    private String state;

    private CommonDialog mPayPop;
    private CommonPopWindow mEmployeePop;
    private CommonPopWindow mLibraryPop;
    private CommonAdapter<WorkerBean> mEmCommonAdapter;
    private CommonAdapter<String> mPayCommonAdapter;
    private CommonAdapter mLibrAdapter;
    private RecyclerView mLibRecyclerView;
    private RecyclerView mPayRecyclerView;
    private RecyclerView mEmRecyclverView;
    private List<String> mPayDatas = new ArrayList<>();
    private List<WorkerBean> mEmDatas = new ArrayList<>();
    private List<QueryLibraryBean> mLibraryDatas = new ArrayList<>();
    private String mId;
    private String mGuid;
    private String whid;
    private String libId;
    private String payType;
    private String haspay;
    private String whname;
    private String libname;

    @Override
    protected int layoutResId() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void init() {
        String orderId = getIntent().getStringExtra(Constans.ORDER_DETAIL_ID);
        String orderGuid = getIntent().getStringExtra(Constans.ORDER_DETAIL_GUID);
        this.mOrderId = orderId;
        this.mOrderGuid = orderGuid;


        mPayPop = new CommonDialog(this, R.layout.dialog_pay_recycler_item);
        mEmployeePop = new CommonPopWindow(this, R.layout.pop_recycler_item);
        mLibraryPop = new CommonPopWindow(this, R.layout.pop_recycler_item);
    }


    @Override
    protected void initView() {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        mPayRecyclerView = mPayPop.getView(R.id.recyclerView);
        mPayRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mPayRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mPayRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        mEmRecyclverView = mEmployeePop.getView(R.id.recyclerView);
        mEmRecyclverView.setLayoutManager(new LinearLayoutManager(this));
        mEmRecyclverView.setItemAnimator(new DefaultItemAnimator());
        mEmRecyclverView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));


        mLibRecyclerView = mLibraryPop.getView(R.id.recyclerView);
        mLibRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mLibRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mLibRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

    }


    @Override
    protected void initData() {
        super.initData();
        mPayDatas.add("支付宝支付");
        mPayDatas.add("微信支付");
        mPayDatas.add("现金支付");
        mPayDatas.add("未付款");

        getPersonDataForService();
        getLibraryDataForService();
    }

    private void getLibraryDataForService() {
        HttpManager.instance()
                .getLibraryQuery(new ReqListLibraryBean())
                .subscribe(new ErrorHandleSubscriber<ArrayList<QueryLibraryBean>>() {
                               @Override
                               public void onNext(@NonNull ArrayList<QueryLibraryBean> queryLibraryBeen) {
                                   parseLibrary(queryLibraryBeen);
                               }
                           }
                );
    }

    private void parseLibrary(@NonNull ArrayList<QueryLibraryBean> queryLibraryBeen) {
        mLibraryDatas.clear();
        mLibraryDatas.addAll(queryLibraryBeen);
        mLibrAdapter.notifyDataSetChanged();

        if (mLibraryDatas.size() == 1) {
            whid = mLibraryDatas.get(0).getId();
            whname = mLibraryDatas.get(0).getName();
            tv_library.setText(whname);
        }

    }

    private void getPersonDataForService() {
        HttpManager.instance()
                .getWorker()
                .subscribe(new ErrorHandleSubscriber<ArrayList<WorkerBean>>() {
                    @Override
                    public void onNext(@NonNull ArrayList<WorkerBean> data) {
                        parseEmployeeData(data);
                    }
                });
    }

    private void parseEmployeeData(List<WorkerBean> mess) {
        mEmDatas.clear();
        mEmDatas.addAll(mess);
        mEmCommonAdapter.notifyDataSetChanged();
    }

    @Override
    protected void updateData() {
        super.updateData();
        getDataFromNet(mOrderId, mOrderGuid);
    }


    private void getDataFromNet(String id, final String guid) {

        Observable.
                zip(
                        HttpManager.instance().getOrderDetail(new ReqQueryOrder(id, guid)),
                        HttpManager.instance().getOrderDetail2(new ReqQueryOrder2(id, guid)),
                        new BiFunction<ArrayList<OrderQueryBean>, ArrayList<OrderQueryBean2>, OrderQueryAllBean>() {
                            @Override
                            public OrderQueryAllBean apply(@NonNull ArrayList<OrderQueryBean> s, @NonNull ArrayList<OrderQueryBean2> s2) throws Exception {
                                return new OrderQueryAllBean(s.get(0), s2);
                            }
                        }
                )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<OrderQueryAllBean>() {
                               @Override
                               public void onNext(@NonNull OrderQueryAllBean s) {
                                   parseData(s.getmBean(), s.getmDatas());
                               }
                           }
                );
    }

    private void parseData(OrderQueryBean orderQueryBean, List<OrderQueryBean2> orderQueryBean2s) {

        mId = orderQueryBean.getId();// ID
        mGuid = orderQueryBean.getGuid(); // GUID
        state = orderQueryBean.getState(); //状态

        if (orderQueryBean.getWhid() != null && orderQueryBean.getWhname() != null) {
            whid = orderQueryBean.getWhid();//仓库ID
            whname = orderQueryBean.getWhname();
            tv_library.setText(whname);
        }
        // 小工ID
        libId = orderQueryBean.getLibid();
        libname = orderQueryBean.getLibname();
        tv_person.setText(libname);
        //支付方式
        payType = orderQueryBean.getPaytype();
        //实付金额
        haspay = orderQueryBean.getHaspay();


        tv_order_num.setText(orderQueryBean.getId());
        tv_order_add_date.setText(orderQueryBean.getAdd_date());

        String str;
        switch (payType == null ? "" : payType) {
            case "0":
                str = "未付款";
                break;
            case "1":
                str = "现金";
                break;
            case "2":
                str = "微信";
                break;
            case "3":
                str = "支付宝";
                break;
            default:
                str = "";
                break;
        }
        tv_pay_method.setText(str);

        tv_yingshou.setText(orderQueryBean.getTotal());
        tv_shishou.setText(orderQueryBean.getHaspay() == null ? "0.00" : orderQueryBean.getHaspay());

        tv_name.setText(orderQueryBean.getBizlnkname());
        tv_address.setText(orderQueryBean.getBizaddr());
        tv_phone.setText(orderQueryBean.getBizmobile());

        notifyData(orderQueryBean2s);

        updateState(state);
    }

    private void updateState(String state) {

        switch (state) {
            case "1"://草稿箱
                btn_commit.setVisibility(View.VISIBLE);
                btn_commit.setText("提交");
                tv_pay_method.setClickable(true);
                tv_library.setClickable(true);
                tv_person.setClickable(true);
                tv_shishou.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                break;
            case "3"://待接收
                btn_commit.setVisibility(View.VISIBLE);
                btn_commit.setText("接收");
                tv_pay_method.setClickable(true);
                tv_library.setClickable(true);
                tv_person.setClickable(true);
                tv_shishou.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                break;
            case "4"://代发货
                btn_commit.setVisibility(View.VISIBLE);
                btn_commit.setText("发货");
                tv_pay_method.setClickable(false);
                tv_library.setClickable(false);
                tv_person.setClickable(false);
                tv_shishou.setInputType(InputType.TYPE_NULL);
                break;
            case "5"://已发货
                btn_commit.setVisibility(View.VISIBLE);
                btn_commit.setText("作废");
                tv_pay_method.setClickable(false);
                tv_library.setClickable(false);
                tv_person.setClickable(false);
                tv_shishou.setInputType(InputType.TYPE_NULL);
                break;
            case "6"://已作废
                btn_commit.setVisibility(View.GONE);
                tv_pay_method.setClickable(false);
                tv_library.setClickable(false);
                tv_person.setClickable(false);
                tv_shishou.setInputType(InputType.TYPE_NULL);
                break;
        }

    }


    private void notifyData(List<OrderQueryBean2> dataBeanList) {
        datas.clear();
        datas.addAll(dataBeanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initListener() {

        commonAdapter = new CommonAdapter<OrderQueryBean2>(this, R.layout.activity_order_detail_item, datas) {
            List<Float> itemCosts = new ArrayList<>();

            @Override
            protected void convert(ViewHolder holder, OrderQueryBean2 bean, int position) {
                TextView tvName = holder.getView(R.id.tv_product_name);
                TextView tvPrice = holder.getView(R.id.tv_product_price);
                TextView tvCount = holder.getView(R.id.tv_product_count);
                TextView tvItemCost = holder.getView(R.id.tv_product_total);
                LinearLayout llTotal = holder.getView(R.id.ll_total);

                tvName.setText(bean.getName());
                tvPrice.setText("￥" + bean.getPrice());
                tvCount.setText(bean.getNum() + bean.getUnit());

                if (TextUtils.isEmpty(bean.getPrice()) || TextUtils.isEmpty(bean.getNum()))
                    return;
                float itemCost = Float.parseFloat(bean.getNum()) * Float.parseFloat(bean.getPrice());
                tvItemCost.setText("￥" + df.format(itemCost));
                itemCosts.add(itemCost);
                if (position == datas.size() - 1) {
                    llTotal.setVisibility(View.VISIBLE);
                    TextView tvTotalCost = holder.getView(R.id.tv_total_cost);
                    float totalCost = 0;
                    for (float b : itemCosts) {
                        totalCost = totalCost + b;
                    }
                    tvTotalCost.setText(df.format(totalCost));

                }
            }
        };
        mRecyclerView.setAdapter(commonAdapter);


        mEmCommonAdapter = new CommonAdapter<WorkerBean>(this, R.layout.pop_category_item2, mEmDatas) {
            @Override
            protected void convert(ViewHolder holder, WorkerBean messBean, int position) {
                TextView tv = holder.getView(R.id.tv);
                tv.setText(messBean.getEname());
            }
        };

        mEmCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                WorkerBean messBean = mEmDatas.get(position);
                libId = messBean.getId();
                libname = messBean.getEname();
                tv_person.setText(messBean.getEname());
                mEmployeePop.dismiss();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;

            }
        });

        mEmRecyclverView.setAdapter(mEmCommonAdapter);


        mLibrAdapter = new CommonAdapter<QueryLibraryBean>(this, R.layout.pop_category_item2, mLibraryDatas) {
            @Override
            protected void convert(ViewHolder holder, QueryLibraryBean messBean, int position) {
                TextView tv = holder.getView(R.id.tv);
                tv.setText(messBean.getName());
            }
        };

        mLibrAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                QueryLibraryBean messBean = mLibraryDatas.get(position);
                whid = messBean.getId();
                whname = messBean.getName();
                tv_library.setText(messBean.getName());
                mLibraryPop.dismiss();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;

            }
        });

        mLibRecyclerView.setAdapter(mLibrAdapter);


        mPayCommonAdapter = new CommonAdapter<String>(this, R.layout.pop_category_item2, mPayDatas) {
            @Override
            protected void convert(ViewHolder holder, String messBean, int position) {
                TextView tv = holder.getView(R.id.tv);
                tv.setText(messBean);
            }
        };
        mPayCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                String pay = mPayDatas.get(position);
                tv_pay_method.setText(pay);

                switch (pay) {
//                    {0：未付款,1：现金,2：刷卡,3:微信,4:支付宝}
                    case "支付宝支付":
                        payType = "4";
                        break;
                    case "微信支付":
                        payType = "3";
                        break;
                    case "刷卡支付":
                        payType = "2";
                        break;
                    case "现金支付":
                        payType = "1";
                        break;
                    case "未付款":
                        payType = "0";
                        break;
                }
                mPayPop.dismiss();
            }


            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mPayRecyclerView.setAdapter(mPayCommonAdapter);

    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("订单");
    }


    @OnClick({R.id.tv_phone, R.id.rl_pay_method, R.id.btn_commit, R.id.tv_pay_method, R.id.tv_library, R.id.tv_person})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.tv_pay_method:
                mPayPop.show();
                break;
            case R.id.tv_library:
                mLibraryPop.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.tv_person:
                mEmployeePop.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.tv_phone:
                callPhone();
                break;
            case R.id.btn_commit:
                switch (state) {
                    case "1": //草稿箱
                        beforeCommit(state);
                        break;
                    case "3"://待接收
                        beforeCommit(state);
                        break;
                    case "4"://待发货
                        send();
                        break;
                    case "5"://已发货
                        cancle();
                        break;
                    case "6"://已作废
                        btn_commit.setVisibility(View.GONE);
                        break;
                }
                break;
            case R.id.rl_back:
                Intent intent = new Intent();
                setResult(0, intent);
                finish();
                break;
            default:

                break;
        }

    }

    //草稿箱 提交之前
    private void beforeCommit(String state) {
        if (TextUtils.isEmpty(payType)) {
            TsUtils.showToast("请选择支付方式");
            return;
        } else if (TextUtils.isEmpty(libId)) {
            libId = "";
        } else if (TextUtils.isEmpty(whid)) {
            TsUtils.showToast("请选择出货仓库");
            return;
        }

        pay(payType);
    }

    //     //草稿箱提交
    private void pay(String payStyle) {
//        {0：未付款,1：现金,2：刷卡,3:微信,4:支付宝}
        switch (payStyle) {
            case "3":
                payOrder();
                break;
            case "2":
                payOrder();
                break;
            case "1":
                postDataToService("1");
                break;
            case "0":
                postDataToService("0");
                break;
            default:
                break;
        }

    }

    private void payOrder() {
        Intent intent = new Intent(this, PayActivity.class);
        intent.putExtra(Constans.EXTRA_PAY_CODE, mId);
        startActivityForResult(intent, Constans.REQUEST_PAY);
    }

    //草稿箱提交
    private void postDataToService(String payStyle) {
        String money = tv_shishou.getText().toString().trim();
        if (money.equals("0.00")) {
            showDialog(payStyle, money);
            return;
        }
        submit(mId, mGuid, "4", whid, whname, libId, libname, payStyle, money);
    }

    /**
     * 提示客户
     *
     * @param payStyle
     * @param money
     */
    private void showDialog(final String payStyle, final String money) {
        new AlertDialog.Builder(this)
                .setMessage("该订单还没有付款，确定要发货吗？")
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                submit(mId, mGuid, "4", whid, whname, libId, libname, payStyle, money);
                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
    }

    //    草稿箱提交
    private void submit(String mID, String mGUID, String state, String mLibraryId, String whname, String mWorkerId, String libname, String payStyle, String mSurePay) {
        HttpManager
                .instance()
                .updateOrder(new ReqUpdateOrder(mID, mGUID, state, mLibraryId, whname, mWorkerId, libname, payStyle, mSurePay))
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                               @Override
                               public void onNext(@NonNull Integer s) {
                                   Intent intent = new Intent();
                                   intent.putExtra(Constans.EXTRA_ORDER_QUERY_DETAIL, "4");
                                   setResult(Constans.REPONS_ORDER_QUERY, intent);
                                   finish();
                               }
                           }
                );
    }

    private void cancle() {
        httpPost("6");
    }

    private void callPhone() {

        if (RexUtils.isMobileNO(tv_phone.getText().toString().trim())) {
            Uri uri = Uri.parse("tel:" + tv_phone.getText().toString().trim());
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_CALL);
            intent.setData(uri);
            startActivity(intent);
        } else {
            Toast.makeText(getApplicationContext(), "手机号格式有误", Toast.LENGTH_SHORT).show();
        }
    }

    //    接收
    private void receive() {
        httpPost("4");//接收
    }

    private void httpPost(final String state) {

        if (payType.equals("2") || payType.equals("3")) {
            Intent intent = new Intent(this, PayActivity.class);
            intent.putExtra(Constans.EXTRA_PAY_CODE, mId);
            startActivityForResult(intent, Constans.REQUEST_PAY);
            return;
        }
        HttpManager
                .instance()
                .updateOrder(new ReqUpdateOrder(mId, mGuid, state, whid, whname, libId, libname, payType, haspay))
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                    @Override
                    public void onNext(@NonNull Integer integer) {
                        Intent intent = new Intent();
                        intent.putExtra(Constans.EXTRA_ORDER_QUERY_DETAIL, state);
                        setResult(Constans.REPONS_ORDER_QUERY, intent);
                        finish();
                    }
                });
    }

    //    接收
    private void send() {
        httpPost("5");//发货
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (data != null) {

            switch (requestCode) {
                case Constans.REQUEST_PAY:
                    break;
            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}
